<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/html" id="tpl-user">
        <div>姓名：{{name}}</div>
        <div>年龄：{{ age }}</div>
        <div>性别：{{ gender}}</div>
        <div>住址：{{address }}</div>
    </script>
</head>

<body>

    <script>
        function myTemplate(id, data) {
            //通过innerHTML 获取标签内的 所有内容
            var str = document.getElementById(id).innerHTML;
            var pattern = /{{\s*([a-zA-Z]+)\s*}}/;

            for (i = 0; i < 1;) {
                str = str.replace(pattern.exec(str)[0], data[pattern.exec(str)[1]])
                    //当在字符串中找不到符合正则表达式的内容是，exec（）的返回值为null，这时打断循环!
                if (pattern.exec(str) == null) {
                    break
                }
            }
            return str
        }
    </script>
    <div id="info"></div>

    <script type="text/javascript">
        // 测试数据
        var data = {
                name: 'zs',
                age: 28,
                gender: '男',
                address: '北京顺义马坡'
            }
            // 通过模板引擎进行编译
        var ret = myTemplate('tpl-user', data)
        console.log(ret)
        var div = document.getElementById('info')
        div.innerHTML = ret
    </script>

</body>

</html>